package com.nintendo.controller;

import com.nintendo.utils.SSEMsgType;
import com.nintendo.utils.SSEServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/sse")
@Slf4j
@CrossOrigin

public class SSEController {
    /**
     * 连接SSE服务的接口
     * @param userId
     * @return
     */
    @GetMapping(path = "connect",produces = {MediaType.TEXT_EVENT_STREAM_VALUE})
    public Object aiOllamaChat(@RequestParam String userId){
        log.info("SSE连接请求，用户ID为: {}", userId);
        return SSEServer.connect(userId);
    }

    /**
     * 发送单条消息给客户端
     * @param userId
     * @param message
     * @return Object
     */
    @GetMapping("/sendMessage")
    public Object sendMessage(@RequestParam String userId, String message){
        SSEServer.sendMessage(userId,message,SSEMsgType.MESSAGE);
        return "OK";
    }
    /**
     * 发送消息给所有客户端用户
     * @param message
     * @return Object
     */
    @GetMapping("/sendMessageAll")
    public Object sendMessage(String message){
        SSEServer.sendMessageToAllUsers(message);
        return "OK";
    }

    /**
     * ADD事件流失输出
     * @param userId
     * @param message
     * @return
     * @throws InterruptedException
     */
    @GetMapping("/sendMessageAdd")
    public Object sendMessageAll(@RequestParam String userId,@RequestParam String message) throws InterruptedException {
        for (int i = 0; i < 10; i++){
            Thread.sleep(200);
            SSEServer.sendMessage(userId,message+"-"+i,SSEMsgType.ADD);
        }
        return "OK";
    }

    /**
     * 停止SSE连接
     * @param userId
     * @return
     * @throws InterruptedException
     */
    @GetMapping("/stop")
    public Object sendMessageAll(@RequestParam String userId) throws InterruptedException {
        SSEServer.stopServer(userId);
        return "OK";
    }

    /**
     * 获取当前在线人数
     * @return
     */
    @GetMapping("/getOnlineCounts")
    public Object getOnlineCounts() {
        return SSEServer.getOnlineCounts();
    }
}
